package com.mmall.controller.backend;

import com.google.common.collect.Maps;
import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.pojo.Product;
import com.mmall.pojo.User;
import com.mmall.service.IFileService;
import com.mmall.service.IProductService;
import com.mmall.service.IUserService;
import com.mmall.util.PropertiesUtil;
import com.mmall.util.QiniuUtils;
import net.sf.jsqlparser.expression.operators.arithmetic.Concat;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.nio.channels.MulticastChannel;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping(value = "/manage/product/")
public class ProductManageController {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IProductService iProductService;

    @Autowired
    private IFileService iFileService;


    /**
     * 产品的更新或者新增
     *
     * @param session
     * @param product
     * @return
     */
    @RequestMapping(value = "insterAndupdateAndProduct.do")
    @ResponseBody
    public ServerResponse insterAndupdateAndProduct(HttpSession session, Product product) {

        //1.用来判断用户是否登录
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorMessage("用户未登录");
        }

        //2.判断用户权限
        ServerResponse adminCount = iUserService.selectAndadmin(user);
        if (adminCount.isSuccess()) {

            //3.是管理员在做业务处理,更新商品名称和id
            return iProductService.insterAndupdateAndProduct(product);
        } else {
            return ServerResponse.createByErrorMessage("无权限操作");
        }
    }


    /**
     * 更新产品的销售状态
     * @param session
     * @param productId
     * @param status
     * @return
     */
    @RequestMapping(value = "updateStatus.do")
    @ResponseBody
    public ServerResponse updateStatus(HttpSession session, Integer productId,Integer status) {

        //1.用来判断用户是否登录
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorMessage("用户未登录");
        }

        //2.判断用户权限
        ServerResponse adminCount = iUserService.selectAndadmin(user);
        if (adminCount.isSuccess()) {

            //3.是管理员在做业务处理,更新商品名称和id
            return iProductService.updateStatus(productId,status);
        } else {
            return ServerResponse.createByErrorMessage("无权限操作");
        }
    }

    /**
     * 根据id查看产品的详情
     * @param session
     * @param productId
     * @return
     */
    @RequestMapping(value = "getDetail.do")
    @ResponseBody
    public ServerResponse getDetail(HttpSession session, Integer productId) {

        //1.用来判断用户是否登录
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorMessage("用户未登录");
        }

        //2.判断用户权限
        ServerResponse adminCount = iUserService.selectAndadmin(user);
        if (adminCount.isSuccess()) {

            //3.是管理员在做业务处理,更新商品名称和id
            return iProductService.getDetail(productId);
        } else {
            return ServerResponse.createByErrorMessage("无权限操作");
        }
    }

    /**
     * 用来进行分页处理
     * @param session
     * @param pageName
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "getList.do")
    @ResponseBody
                                                     //指定对应的差数,pageName默认第一页  ,pageSize 默认一页展示10条数据
    public ServerResponse getList(HttpSession session, @RequestParam(value = "pageName",defaultValue = "1") Integer pageName, @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize) {

        //1.用来判断用户是否登录
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorMessage("用户未登录");
        }

        //2.判断用户权限
        ServerResponse adminCount = iUserService.selectAndadmin(user);
        if (adminCount.isSuccess()) {

            //3.是管理员在做业务处理,更新商品名称和id
            return iProductService.getList(pageName,pageSize);
        } else {
            return ServerResponse.createByErrorMessage("无权限操作");
        }
    }

    /**
     * 前台搜索加分页功能
     * @param session
     * @param productName
     * @param productId
     * @param pageName
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "searchProduct.do")
    @ResponseBody
    //指定对应的差数,pageName默认第一页  ,pageSize 默认一页展示10条数据
    public ServerResponse searchProduct(HttpSession session,String productName,Integer productId, @RequestParam(value = "pageName",defaultValue = "1") Integer pageName, @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize) {

        //1.用来判断用户是否登录
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorMessage("用户未登录");
        }

        //2.判断用户权限
        ServerResponse adminCount = iUserService.selectAndadmin(user);
        if (adminCount.isSuccess()) {

            //3.是管理员在做业务处理,更新商品名称和id
            return iProductService.searchProduct(productName,productId,pageName,pageSize);
        } else {
            return ServerResponse.createByErrorMessage("无权限操作");
        }
    }


    /**
     * springmvc文件上传
     * @param session
     * @param request
     * @param file
     * @return
     */
    @RequestMapping(value = "upload.do")
    @ResponseBody
    //指定对应的差数,pageName默认第一页  ,pageSize 默认一页展示10条数据
    public ServerResponse upload(HttpSession session, HttpServletRequest request, @RequestParam(value = "upload_file",required = false) MultipartFile file) {

        //1.用来判断用户是否登录
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorMessage("用户未登录");
        }

        //2.判断用户权限
        ServerResponse adminCount = iUserService.selectAndadmin(user);
        if (adminCount.isSuccess()) {

//            //3.是管理员在做业务处理,图片上传
//
//            //4.用来在项目中读取文件夹
//            String path = request.getSession().getServletContext().getRealPath("upload");
//            //文件上传返回的结果
//            String trageName = iFileService.upload(file,path);
//
//

//            //上传服务器地址拼接
//            String url = PropertiesUtil.getProperty("ftp.server.http.prefix")+trageName;
//
//            //封装数据
//            HashMap map = Maps.newHashMap();
//            map.put("uri", trageName);
//            map.put("url",url );
//            return  ServerResponse.createBySuccess(map);

            //1.获得文件名
            String filename = file.getOriginalFilename();
            //2.改成唯一uuid的文件名
            String Newfilename = UUID.randomUUID().toString()+filename.substring(filename.lastIndexOf("."));

            try {
                QiniuUtils.upload2Qiniu(file.getBytes(), Newfilename);
            } catch (IOException e) {
                e.printStackTrace();
            }

        return  ServerResponse.createBySuccessMessage("上传成功");
        } else {
            return ServerResponse.createByErrorMessage("无权限操作");
        }
    }

    /**
     * 富文本上传
     * @param session
     * @param request
     * @param file
     * @param response
     * @return
     */
    @RequestMapping(value = "richtextImgUpload.do")
    @ResponseBody
    //指定对应的差数,pageName默认第一页  ,pageSize 默认一页展示10条数据
    public Map richtextImgUpload(HttpSession session, HttpServletRequest request, @RequestParam(value = "upload_file",required = false) MultipartFile file, HttpServletResponse response) {

        HashMap map = Maps.newHashMap();
        //1.用来判断用户是否登录
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            map.put("seccess", false);
            map.put("msg","请登录管理员账号" );
            return map;
        }

        //富文本中对于返回值有自己的要求,我们使用是simditor所以按照simditor的要求进行返回
//        {
//            "success": true/false,
//                "msg": "error message", # optional
//            "file_path": "[real file path]"
//        }

        //2.判断用户权限
        ServerResponse adminCount = iUserService.selectAndadmin(user);
        if (adminCount.isSuccess()) {

            //3.是管理员在做业务处理,图片上传

            //4.用来在项目中读取文件夹
            String path = request.getSession().getServletContext().getRealPath("upload");
            //文件上传返回的结果
            //String trageName = iFileService.upload(file,path);
            if (StringUtils.isBlank(null)){
                map.put("seccess", false);
                map.put("msg","上传失败" );
                return  map;
            }

            //上传服务器地址拼接
            String url = PropertiesUtil.getProperty("ftp.server.http.prefix")+null;



            map.put("success",true );
            map.put("msg", "文件上传成功");
            map.put("file_path",url );
            response.addHeader("Access-Control-Allow-Headers","X-File-Name");
            return  map;

        } else {
            map.put("sussess",false );
            map.put("msg","无权限操作" );
            return map;
        }
    }
}
